package com.st.mall.elasticsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.st.common.dubboProvider.elasticsearch.UpTo;
import com.st.common.to.es.SkuEsModel;
import com.st.common.utils.R;
import com.st.mall.elasticsearch.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@DubboService(interfaceClass = UpTo.class)
@Slf4j
public class EsUpToServiceImpl implements UpTo {
    //    @Autowired
//    private RestHighLevelClient client;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public R upTo(List<SkuEsModel> skuEsModels) {
        //索引名字
        String indexName = EsConstant.PRODUCT_INDEX;
        HttpHeaders headers = new HttpHeaders();
        //json类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        //循环添加进es
        for (SkuEsModel skuEsModel : skuEsModels) {
            //将headers和对象封装进HttpEntity
            HttpEntity<SkuEsModel> requestEntity = new HttpEntity<>(skuEsModel, headers);
            try {
                //restTemplate的postForObject放入product对象，并以skuEsModel.getSkuId()为_id，String.class指定返回信息为字符串类型
                String s = restTemplate.postForObject("http://192.168.56.10:9200/" + indexName + "/_doc/" + skuEsModel.getSkuId(),
                        requestEntity, String.class);
            } catch (RestClientException e) {
                // 存储失败的SkuEsModel对象可以记录到日志中或者抛出异常进行处理
                log.error("存储失败的skuId失败: " + skuEsModel.getSkuId());
                e.printStackTrace();
            }
        }
        return R.ok().put("code",10000);
    }
}
